package com.maezia.tdr.controller;

import com.alibaba.fastjson.JSONObject;
import com.maezia.tdr.common.Result;
import com.maezia.tdr.common.annotation.Loggable;
import com.maezia.tdr.common.enums.StatusCodeEnum;
import com.maezia.tdr.common.exception.DriveException;
import com.maezia.tdr.domain.dto.ReportInfoDto;
import com.maezia.tdr.domain.po.ClientDetails;
import com.maezia.tdr.domain.vo.ReportVo;
import com.maezia.tdr.service.ReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@Slf4j
@Api(value = "报告数据相关接口",tags = "报告数据管理")
@RestController
public class ReportController extends BaseController {

    @Autowired
    private ReportService reportService;

    @Loggable
    @ApiOperation(value="获取试驾数据接口", httpMethod= "POST")
    @PostMapping("/get-test-drive-data")
    public Result<ReportVo> getReportInfo(@RequestBody @Valid ReportInfoDto reportInfo) throws Exception {
        log.info("reportInfo JSON:{}", JSONObject.toJSONString(reportInfo));

        if(reportInfo.getVehicleId().length() > 64){
            throw new DriveException(StatusCodeEnum.VEHICLE_ID_64_LENGTH);
        }

        if(!"true".equals(reportInfo.getConsentState()) && !"false".equals(reportInfo.getConsentState())){
            throw new DriveException(StatusCodeEnum.INVALID_CONSENT_FORMAT);
        }
        ClientDetails userInfo = getCurrentUser();
        reportInfo.setAppKey(userInfo.getClientId());
        return Result.success(reportService.getReportInfo(reportInfo));
    }

    @Loggable
    @ApiOperation(value="获取试驾数据接口", httpMethod= "GET")
    @ApiImplicitParams({ @ApiImplicitParam(name="id",value="试驾唯一标识",dataType="string")})
    @GetMapping("/getById")
    public Result<ReportVo> getReportById(String id) throws DriveException {
        if(StringUtils.isEmpty(id)){
            throw new DriveException("试驾唯一标识不能为空");
        }

        return Result.success(reportService.getReportVo(id));
    }
}
